package org.web.ctrlcv.chatting.controller;

import java.util.Collection;
import java.util.Iterator;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.ScriptProxy;
import org.web.ctrlcv.chatting.vo.ChattingVO;
import javax.servlet.http.HttpSession;

public class DwrChattingController {
	//시작
	public void start() throws Exception {
		System.out.println("<!> start ");
		ChattingVO chattingVO = new ChattingVO();
		HttpSession session = WebContextFactory.get().getHttpServletRequest().getSession();
		String user_name = (String)session.getAttribute("USER_NAME");
		chattingVO.setMessage(user_name+" 님이 입장하셨습니다.");
		chattingVO.setName("System");
		
		notifyAllClients("messageReceived", chattingVO);
	}
	
	//메세지보내기
	public void send(ChattingVO chattingVO) throws Exception {
		System.out.println("<!> send ");
		//연결된 클라이언트로 Push
		HttpSession session = WebContextFactory.get().getHttpServletRequest().getSession();
		String user_name = (String)session.getAttribute("USER_NAME");
		chattingVO.setName(user_name);
	    notifyAllClients("messageReceived", chattingVO);
	}
	
	//종료
	public void end() throws Exception {
		System.out.println("<!> end ");
		ChattingVO chattingVO = new ChattingVO();
		HttpSession session = WebContextFactory.get().getHttpServletRequest().getSession();
		String user_name = (String)session.getAttribute("USER_NAME");
		chattingVO.setMessage(user_name+" 님이 퇴장하셨습니다.");
		chattingVO.setName("System");
		
		notifyAllClients("messageReceived", chattingVO);
	}
	
	//연결 된 클라이언트로 push
	private void notifyAllClients(String eventType, ChattingVO chattingVO) {
		System.out.println("<!> notifyAllClients");
		getScriptProxy().addFunctionCall(eventType, chattingVO);
	}
	
	//연결 된 클라이언트 조회
	private ScriptProxy getScriptProxy() {
		System.out.println("<!> getScriptProxy");
		WebContext context = WebContextFactory.get();
		Collection sessions = context.getScriptSessionsByPage(context.getCurrentPage());
		
		return new ScriptProxy(sessions);
	}
}
